package com.wbxqy.car_management_system.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wbxqy.car_management_system.entity.Department;
import com.wbxqy.car_management_system.entity.User;
import com.wbxqy.car_management_system.service.IDepartmentService;
import com.wbxqy.car_management_system.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wbxqy.car_management_system.utils.JwtTokenUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 用户表 前端控制器
 *
 * @author wbxqy
 * @since 2024-07-04
 */
@RestController
@RequestMapping("/wbxqy/users")
public class UserController {
    private static final Logger log = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private IUserService userService;
    @Autowired
    private IDepartmentService departmentService;

    @PostMapping
    public boolean addUser(@RequestBody User user) {
        user.setStatusWbxqy("U");
        return userService.save(user);
    }

    @DeleteMapping("/{id}")
    public boolean deleteUser(@PathVariable Integer id) {
        return userService.removeById(id);
    }

    @PutMapping
    public boolean updateUser(@RequestBody User user) {
        return userService.updateById(user);
    }

    @GetMapping("/{id}")
    public User getUserById(@PathVariable Integer id) {
        return userService.getByIdWithDepartment(id);
    }

    @GetMapping("/page")
    public Page<User> getAllUsersPage(
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String phoneNumber,
            @RequestParam(required = false) String email,
            @RequestParam(required = false) String role) {
        Page<User> pageInfo = new Page<>(page, pageSize);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();

        if (username != null && !username.isEmpty()) {
            queryWrapper.like("username_wbxqy", username);
        }
        if (phoneNumber != null && !phoneNumber.isEmpty()) {
            queryWrapper.like("phone_number_wbxqy", phoneNumber);
        }
        if (email != null && !email.isEmpty()) {
            queryWrapper.like("email_wbxqy", email);
        }
        if (role != null && !role.isEmpty()) {
            queryWrapper.eq("role_wbxqy", role);
        }

        Page<User> userPage = userService.page(pageInfo, queryWrapper);

        // 查询每个用户的部门信息并设置到用户对象中
        userPage.getRecords().forEach(user -> {
            Department department = departmentService.getById(user.getDepartmentIdWbxqy());
            user.setDepartment(department);
        });

        return userPage;
    }

    @GetMapping("")
    public List<User> list(@RequestParam(required = false) String role) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();

        if (role != null && !role.isEmpty()) {
            queryWrapper.eq("role_wbxqy", role);
        }
        return userService.list(queryWrapper);
    }


    /**
     * 注册
     *
     * @param user
     * @return
     */
    @PostMapping("/register")
    public boolean register(@RequestBody User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username_wbxqy", user.getUsernameWbxqy());
        if (userService.getOne(queryWrapper) != null) {
            return false;
        }
        user.setPasswordWbxqy(user.getPasswordWbxqy());
        return userService.save(user);
    }

    /**
     * 登录
     *
     * @param username
     * @param password
     * @return
     */
    @GetMapping("/login")
    public String login(@RequestParam String username, @RequestParam String password) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username_wbxqy", username);
        User user = userService.getOne(queryWrapper);
        if (user != null && password.equals(user.getPasswordWbxqy())) {
            user.setDepartment(departmentService.getById(user.getDepartmentIdWbxqy()));
            return JwtTokenUtil.generateToken(JSON.toJSONString(user));
        }
        return null;
    }

    @GetMapping("/userInfo")
    public String getUserInfoTwo(HttpServletRequest request) {
        // 根据用户名获取用户信息
        String token = request.getHeader("Authorization");
        final JSONObject tokenObj = (JSONObject) JSON.parse(JwtTokenUtil.getUsernameFromJWT(token));
        final User user = userService.getById(tokenObj.get("userIdWbxqy").toString());
        return JSON.toJSONString(user);
    }

    @GetMapping("/isRight")
    public Boolean checkPassword(HttpServletRequest request, @RequestParam String password) {
        // 根据用户名获取用户信息
        String token = request.getHeader("Authorization");
        final JSONObject tokenObj = (JSONObject) JSON.parse(JwtTokenUtil.getUsernameFromJWT(token));
        final User user = userService.getById(tokenObj.get("userIdWbxqy").toString());
        return user.getPasswordWbxqy().equals(password);
    }

    @PutMapping("/changePassword")
    public Boolean changePassword(HttpServletRequest request, @RequestBody User user) {
        // 根据用户名获取用户信息
        String token = request.getHeader("Authorization");
        final JSONObject tokenObj = (JSONObject) JSON.parse(JwtTokenUtil.getUsernameFromJWT(token));
        final User userALl = userService.getById(tokenObj.get("userIdWbxqy").toString());
        userALl.setPasswordWbxqy(user.getPasswordWbxqy());
        userService.updateById(userALl);
        return true;
    }


    @PutMapping("/returned")
    public Boolean returned(HttpServletRequest request, @RequestBody User user) {
        // 根据用户名获取用户信息
        String token = request.getHeader("Authorization");
        final JSONObject tokenObj = (JSONObject) JSON.parse(JwtTokenUtil.getUsernameFromJWT(token));
        final User userALl = userService.getById(tokenObj.get("userIdWbxqy").toString());
        userALl.setStatusWbxqy("N");
        userService.updateById(userALl);
        return true;
    }


}
